package view;

import dao.Blog;
import dao.BlogDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/blogList.html")
public class BlogList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession(false) == null){
            resp.sendRedirect("login.html");
            return;
        }
        resp.setContentType("text/html; charset=utf-8");
        BlogDao blogDao = new BlogDao();
        try {
            List<Blog> list = blogDao.selectAll();
            System.out.println(list);
            ServletContext context = this.getServletContext();
            TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
            WebContext webContext = new WebContext(req,resp,context);
            webContext.setVariable("blogs",list);
            String html = engine.process("blogList",webContext);
            System.out.println(html);
            resp.getWriter().write(html);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
